import 'package:fate_blind_box/routes/page_route_names.dart';
import 'package:fate_blind_box/theme/theme_color.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:fluwx/fluwx.dart' as fluwx;
import 'package:get/get.dart';
import 'package:im_flutter_sdk/im_flutter_sdk.dart';
import 'package:just_audio/just_audio.dart';
import 'package:roundcheckbox/roundcheckbox.dart';

import '../../network/Api.dart';
import '../../network/http_config.dart';
import '../../utils/loading.dart';
import '../../utils/provider.dart';
import 'Login_pass.dart';
import 'Login_register.dart';
import 'WebView.dart';
import 'agreenApp.dart';
import 'login_by_pwd_controller.dart';

class LoginByPwd extends StatefulWidget {
  const LoginByPwd({Key? key}) : super(key: key);

  @override
  State createState() {
    return _LoginPwdPageState();
  }
}

class _LoginPwdPageState extends State<LoginByPwd> {
  bool aaa = false;

  // 登录按钮颜色选择器
  var _loginBtnSelector = [0xFFF5F6F6, 0xFF222222];
  final _loginBtnEnable = [0xFFFB6D99, 0xFFFFFFFF];
  final _loginBtnUnable = [0xFFF5F6F6, 0xFF222222];

  final TextEditingController _mobController = TextEditingController();
  final TextEditingController _pwdController = TextEditingController();
  final player = AudioPlayer();

  bool check = false;
  bool _isObscure = true;
  Color _eyeColor = Colors.grey;
  final dd = '';

  LoginByPwdController controller = Get.put(LoginByPwdController());

  getCheckBoxBorderColor() {
    if (check) {
      return ThemeColor.colorCF8F23;
    } else {
      return const Color(0xFFD1D1D1);
    }
  }

  @override
  void initState() {
    super.initState();

    if (Provider.xieyi.isNotEmpty) {
      WidgetsBinding.instance
          .addPostFrameCallback((_) => AgreenDialog.showUpdateDialog(context));
    }
    controller.isHasWechat();

    //如果token存在，免登录
    // _isLogin();
    initWechatLogin();
  }

  void initWechatLogin() async {
    //初始化微信
    await _initWechat();
  }

  Future? _initWechat() async {
    return fluwx.registerWxApi(
        appId: Provider.wechatAppID,
        doOnAndroid: true,
        doOnIOS: true,
        universalLink: HttpConfig.baseUrl
        // universalLink: "${HttpConfig.baseUrl}ios"
        );
  }

  _sendlogin() {
    FocusScope.of(context).unfocus();
    if (!_verify(true)) {
      return;
    }
    loading(() async {
      final res = await Api.getInstance()
          .passloginBySms(_mobController.text, _pwdController.text);
      if (res['code'] == 0) {
        final data = res['data'];
        Provider.memberId = data['memberId'];
        Provider.memberInfo = data;
        HttpConfig.token = data['token'];
        Provider.userEaseName = data['emUser']['username'];
        Provider.userEaseToken = data['userEaseToken'];
        await Provider.cache("memberId", Provider.memberId);
        await Provider.cache("token", HttpConfig.token);
        await Provider.cache("username", Provider.userEaseName);
        await Provider.cache("userEaseToken", Provider.userEaseToken);

        if (kDebugMode) {
          print('rx--环信用户id-------' + Provider.userEaseName);
          print('rx----环信token-----' + Provider.userEaseToken);
        }
        if (await EMClient.getInstance.isConnected()) {
        } else {
          await EMClient.getInstance
              .login(Provider.userEaseName, Provider.userEaseToken, false);
        }
        String? inviteCode = await Provider.getCache("inviteCode");
        if (inviteCode?.isNotEmpty == true) {
          await Api.getInstance().invite(Provider.memberId, inviteCode!);
        }
        Get.offAllNamed(PageRouteNames.main);
      }
      toast(res['msg']);
    });
  }

  bool _verify(bool sendCode) {
    if (_mobController.text.length < 11) {
      toast("请输入手机号");
      return false;
    }
    if (_pwdController.text.isEmpty) {
      toast("请输入密码");
      return false;
    }
    if (this.check == false) {
      // toast("请仔细阅读并了解《隐私协议》和《服务协议》");
      _versionOfdown(context, "请仔细阅读并了解《隐私协议》和《服务协议》");
      return false;
    }
    return true;
  }

  Future<void> _versionOfdown(context, String title) async {
    showCupertinoDialog(
        context: context,
        builder: (context) {
          return CupertinoAlertDialog(
            title: Text.rich(TextSpan(children: [
              const TextSpan(
                  text: "请仔细阅读",
                  style: TextStyle(color: Color(0xFF222222), fontSize: 12)),
              TextSpan(
                text: "《隐私协议》",
                style: TextStyle(color: ThemeColor.colorCF8F23, fontSize: 12),
                recognizer: TapGestureRecognizer()
                  ..onTap = () {
                    Navigator.push(context,
                        MaterialPageRoute(builder: (BuildContext context) {
                      return const Browser(
                          '隐私协议', '${HttpConfig.baseUrl}priva');
                    }));
                  },
              ),
              const TextSpan(
                  text: "和",
                  style: TextStyle(color: Color(0xFF222222), fontSize: 12)),
              TextSpan(
                text: "《服务协议》",
                style: TextStyle(color: ThemeColor.colorCF8F23, fontSize: 12),
                recognizer: TapGestureRecognizer()
                  ..onTap = () {
                    Navigator.push(context,
                        MaterialPageRoute(builder: (BuildContext context) {
                      return const Browser('服务协议', '${HttpConfig.baseUrl}serv');
                    }));
                  },
              )
            ])),
            actions: <Widget>[
              CupertinoDialogAction(
                onPressed: () {
                  Navigator.pop(context);
                },
                child: const Text(
                  '不同意',
                  style: TextStyle(fontSize: 16, color: Colors.black),
                ),
              ),
              CupertinoDialogAction(
                onPressed: () {
                  print('bbbb');
                  Navigator.pop(context);
                  setState(() {
                    check = true;
                  });
                  _sendlogin();
                },
                child: Text(
                  '同意并继续',
                  style: TextStyle(fontSize: 16, color: ThemeColor.colorCF8F23),
                ),
              ),
            ],
          );
        });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: SingleChildScrollView(
        child: Stack(
          children: [
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Container(
                  margin: const EdgeInsets.only(top: 80),
                  child: const Center(
                    child: Image(
                      width: 96,
                      height: 96,
                      image: AssetImage("images/new_logo.png"),
                    ),
                  ),
                ),
                const SizedBox(height: 12),
                // 标题
                const Center(
                  child: Text(
                    "都肆商圈",
                    style: TextStyle(fontSize: 16, color: Color(0xFF3A3A3A)),
                  ),
                ),
                // 手机号
                Container(
                  margin: const EdgeInsets.fromLTRB(40, 16, 40, 0),
                  height: 45,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(5),
                    color: const Color(0xFFF6F8FA),
                  ),
                  child: TextField(
                    controller: _mobController,
                    maxLength: 11,
                    keyboardType: TextInputType.phone,
                    cursorColor: const Color(0xFFFB6D99),
                    style:
                        const TextStyle(fontSize: 12, color: Color(0xFF222222)),
                    decoration: InputDecoration(
                      hintText: "请输入您的手机号",
                      counterText: "",
                      border: InputBorder.none,
                      hintStyle: const TextStyle(color: Color(0xFF999999)),
                      fillColor: const Color(0xffF6F8FA),
                      filled: true,
                      enabledBorder: const OutlineInputBorder(
                        /*边角*/
                        borderRadius: BorderRadius.all(
                          Radius.circular(5), //边角为30
                        ),
                        borderSide: BorderSide(
                          color: Colors.white54, //边线颜色为黄色
                          width: 1, //边线宽度为2
                        ),
                      ),
                      focusedBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(5),
                        borderSide: const BorderSide(
                          color: Colors.white54, //边框颜色为绿色
                          width: 1, //宽度为5
                        ),
                      ),
                      contentPadding:
                          const EdgeInsets.only(top: 0, bottom: 0, left: 10),
                    ),
                    onChanged: (e) {
                      setState(() {
                        _loginBtnSelector =
                            _pwdController.text.length >= 6 && e.length >= 11
                                ? _loginBtnEnable
                                : _loginBtnUnable;
                      });
                    },
                  ),
                ),
                // 密码
                Container(
                  margin: const EdgeInsets.fromLTRB(40, 12, 40, 0),
                  height: 45,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(5),
                    color: const Color(0xFFF6F8FA),
                  ),
                  child: TextField(
                    controller: _pwdController,
                    maxLength: 16,
                    obscureText: _isObscure,
                    keyboardType: TextInputType.text,
                    cursorColor: ThemeColor.mainColor,
                    style: TextStyle(fontSize: 12, color: ThemeColor.textColor),
                    decoration: InputDecoration(
                      hintText: "请输入您的密码",
                      counterText: "",
                      border: InputBorder.none,
                      hintStyle: TextStyle(color: ThemeColor.textColorSecond),
                      fillColor: const Color(0xffF6F8FA),
                      filled: true,
                      enabledBorder: const OutlineInputBorder(
                        /*边角*/
                        borderRadius: BorderRadius.all(
                          Radius.circular(5), //边角为30
                        ),
                        borderSide: BorderSide(
                          color: Colors.white54, //边线颜色为黄色
                          width: 1, //边线宽度为2
                        ),
                      ),
                      focusedBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(5),
                        borderSide: const BorderSide(
                          color: Colors.white54, //边框颜色为绿色
                          width: 1, //宽度为5
                        ),
                      ),
                      contentPadding:
                          const EdgeInsets.only(top: 0, bottom: 0, left: 10),
                      suffixIcon: IconButton(
                        icon: Icon(
                          _isObscure ? Icons.visibility_off : Icons.visibility,
                          color: _eyeColor,
                        ),
                        onPressed: () {
                          setState(() {
                            _isObscure = !_isObscure;
                            _eyeColor = (_isObscure
                                ? Colors.grey
                                : Theme.of(context).iconTheme.color)!;
                          });
                        },
                      ),
                    ),
                    onChanged: (e) {
                      setState(() {
                        _loginBtnSelector =
                            _mobController.text.length >= 11 && e.length >= 6
                                ? _loginBtnEnable
                                : _loginBtnUnable;
                      });
                    },
                  ),
                ),
                //忘记密码
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    GestureDetector(
                      child: Container(
                          margin: const EdgeInsets.only(left: 40.0),
                          height: 48,
                          child: const Center(
                            child: Text(
                              "忘记密码",
                              style: TextStyle(
                                  fontSize: 13, color: Color(0xFF222222)),
                            ),
                          )),
                      onTap: () {
                        Navigator.push(
                            context,
                            MaterialPageRoute(
                                builder: (context) => const passLoginUI()));
                      },
                    ),
                    GestureDetector(
                      child: Container(
                          margin: const EdgeInsets.only(right: 40.0),
                          height: 48,
                          child: Center(
                            child: Text(
                              "新用户注册",
                              style: TextStyle(
                                fontSize: 13,
                                color: ThemeColor.colorCF8F23,
                              ),
                            ),
                          )),
                      onTap: () {
                        Navigator.of(context).push(MaterialPageRoute(
                            builder: (ctx) => const registerLoginUI()));
                      },
                    ),
                  ],
                ),
                // 登录按钮
                GestureDetector(
                  child: Container(
                      margin: const EdgeInsets.fromLTRB(40, 10, 40, 0),
                      height: 42,
                      decoration: ShapeDecoration(
                        shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(22.5)),
                        color: ThemeColor.colorCF8F23,
                      ),
                      width: double.maxFinite,
                      child: const Center(
                        child: Text(
                          "登录",
                          style: TextStyle(color: Colors.white, fontSize: 15),
                        ),
                      )),
                  onTap: () {
                    _sendlogin();
                  },
                ),

                //隐私协议、服务协议
                Column(
                  children: [
                    GestureDetector(
                      onTap: () {
                        if (check) {
                          check = false;
                        } else {
                          check = true;
                        }
                        setState(() {});
                      },
                      child: Container(
                        margin: const EdgeInsets.only(left: 60, right: 60),
                        padding: const EdgeInsets.only(top: 14),
                        color: Colors.white,
                        child: Row(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            RoundCheckBox(
                              size: 16,
                              //checkBox大小
                              checkedWidget: const Icon(
                                Icons.check,
                                color: Colors.white,
                                size: 8,
                              ),
                              checkedColor: ThemeColor.colorCF8F23,
                              uncheckedColor: Colors.white,
                              border: Border.all(
                                  color: getCheckBoxBorderColor(), width: 1),
                              isChecked: check,
                              onTap: (selected) {
                                if (check) {
                                  check = false;
                                } else {
                                  check = true;
                                }
                                setState(() {});
                              },
                            ),
                            const SizedBox(
                              width: 3,
                            ),
                            const Center(
                                child: Text.rich(TextSpan(children: [
                              TextSpan(
                                text: "登录即代表您同意我们的",
                                style: TextStyle(
                                    color: Color(0xFFCECECE), fontSize: 12),
                              ),
                            ]))),
                          ],
                        ),
                      ),
                    ),
                    const SizedBox(
                      height: 5,
                    ),
                    Center(
                        child: Text.rich(TextSpan(children: [
                      TextSpan(
                        text: "《隐私协议》",
                        style: TextStyle(
                            color: ThemeColor.colorCF8F23, fontSize: 10),
                        recognizer: TapGestureRecognizer()
                          ..onTap = () {
                            Navigator.push(context, MaterialPageRoute(
                                builder: (BuildContext context) {
                              return const Browser(
                                  '隐私协议', '${HttpConfig.baseUrl}priva');
                            }));
                          },
                      ),
                      TextSpan(
                        text: "《服务协议》",
                        style: TextStyle(
                            color: ThemeColor.colorCF8F23, fontSize: 10),
                        recognizer: TapGestureRecognizer()
                          ..onTap = () {
                            Navigator.push(context, MaterialPageRoute(
                                builder: (BuildContext context) {
                              return const Browser(
                                  '服务协议', '${HttpConfig.baseUrl}serv');
                            }));
                          },
                      )
                    ]))),
                  ],
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
